# -*- coding: utf-8 -*-

import json
import logging
from datetime import datetime
from odoo import http, fields
from odoo.http import request
from odoo.exceptions import ValidationError, AccessError
from .api_base import api_response, verify_api_token, check_api_permission, check_department_permission
import io

_logger = logging.getLogger(__name__)


class DeviceManagementController(http.Controller):
    """设备培训、巡检、验证、校准统一管理控制器"""

    # ==================== 设备培训管理 ====================

    @http.route('/api/training/list', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:training:list')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def list_training(self, **kwargs):
        """获取设备培训列表"""
        page = kwargs.get('pageNum', 1)
        size = kwargs.get('pageSize', 10)
        equipment_id = kwargs.get('equipmentId', '')
        equipment_name = kwargs.get('equipmentName', '')
        trainer_name = kwargs.get('trainerName', '')
        training_mode = kwargs.get('trainingMode', '')
        status = kwargs.get('status', '')

        domain = []
        if equipment_id:
            domain.append(('equipment_id', '=', int(equipment_id)))
        if equipment_name:
            domain.append(('equipment_name', 'ilike', equipment_name))
        if trainer_name:
            domain.append(('trainer_name', 'ilike', trainer_name))
        if training_mode:
            domain.append(('training_mode', '=', training_mode))
        if status:
            domain.append(('status', '=', status))

        # 部门权限过滤
        current_user = getattr(request, 'current_api_user', None)
        if current_user:
            # 检查是否是admin账号，admin账号拥有全部权限
            if hasattr(current_user, 'is_admin') and current_user.is_admin:
                # admin账号可以看到所有培训记录，不添加过滤条件
                pass
            else:
                user_department = current_user.department_id
                if user_department:
                    # 检查用户是否是部门负责人
                    is_department_leader = user_department.leader_id and user_department.leader_id.id == current_user.id

                    if is_department_leader:
                        # 部门负责人：可以看到该部门下的所有设备相关培训
                        domain.append(('department_id', '=', user_department.id))
                    else:
                        # 非部门负责人：只能看到设备绑定用户为自己的培训记录
                        equipment_ids = request.env['device.equipment'].search([
                            ('user_id', '=', current_user.id)
                        ]).ids
                        if equipment_ids:
                            domain.append(('equipment_id', 'in', equipment_ids))
                        else:
                            # 如果没有绑定设备，返回空结果
                            domain.append(('id', '=', False))
                else:
                    # 没有部门信息，返回空结果
                    domain.append(('id', '=', False))

        # 计算总数
        total = request.env['device.training'].sudo().search_count(domain)

        # 获取数据
        offset = (page - 1) * size
        trainings = request.env['device.training'].sudo().search(domain, offset=offset, limit=size,
                                                                 order='training_date desc')

        # 构建返回数据
        rows = []
        for training in trainings:
            rows.append({
                'trainingId': training.id,
                'equipmentId': training.equipment_id.id,
                'equipmentName': training.equipment_name,
                'equipmentCode': training.equipment_code,
                'equipmentCategory': training.equipment_category,
                'trainingDate': training.training_date.strftime('%Y-%m-%d') if training.training_date else '',
                'trainingContent': training.training_content or '',
                'trainingMode': training.training_mode,
                'trainerId': training.trainer_id.id if training.trainer_id else None,
                'trainerName': training.trainer_name,
                'participantCount': training.participant_count,
                'departmentId': training.department_id.id if training.department_id else None,
                'departmentName': training.department_name,
                'status': training.status,
                'durationHours': training.duration_hours,
                'trainingLocation': training.training_location or '',
                'trainingScore': training.training_score,
                'createTime': training.create_time.strftime('%Y-%m-%d %H:%M:%S') if training.create_time else '',
                'remark': training.remark or ''
            })
        return {
            'code': 200,
            'message': '',
            'data': {
                'total': total,
                'rows': rows
            }
        }

    @http.route('/api/training/add', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:training:add')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def add_training(self, **kwargs):
        """新增培训记录"""
        equipment_id = kwargs.get('equipmentId')
        training_date = kwargs.get('trainingDate')
        training_content = kwargs.get('trainingContent')
        training_mode = kwargs.get('trainingMode', 'offline')
        trainer_id = kwargs.get('trainerId')
        participant_count = kwargs.get('participantCount', 1)
        department_id = kwargs.get('departmentId')
        duration_hours = kwargs.get('durationHours', 1.0)
        training_location = kwargs.get('trainingLocation', '')
        remark = kwargs.get('remark', '')

        if not equipment_id or not training_date or not training_content or not trainer_id or not department_id:
            raise ValidationError('设备、培训日期、培训内容、培训师、参与部门为必填项')

        vals = {
            'equipment_id': int(equipment_id),
            'training_date': datetime.strptime(training_date, '%Y-%m-%d').date(),
            'training_content': training_content,
            'training_mode': training_mode,
            'trainer_id': int(trainer_id),
            'participant_count': int(participant_count),
            'department_id': int(department_id),
            'duration_hours': float(duration_hours),
            'training_location': training_location,
            'remark': remark
        }

        training = request.env['device.training'].sudo().create(vals)
        return {
            'code': 200,
            'message': '',
            'data': {'trainingId': training.id}
        }

    @http.route('/api/training/export', type='http', auth='none', methods=['GET'], csrf=False, cors='*')
    @verify_api_token
    # @check_api_permission('device:training:export')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def export_training(self, **kwargs):
        """导出培训信息"""
        trainings = request.env['device.training'].sudo().search([])

        # 构建Excel数据
        import xlsxwriter
        output = io.BytesIO()
        workbook = xlsxwriter.Workbook(output)
        worksheet = workbook.add_worksheet('设备培训信息')

        # 设置标题
        headers = [
            '设备编号', '设备名称', '设备类别', '培训日期', '培训内容', '培训形式',
            '培训师', '参与人数', '参与部门', '培训时长(h)', '培训地点', '培训评分',
            '培训状态', '创建时间', '备注'
        ]

        # 写入标题
        for col, header in enumerate(headers):
            worksheet.write(0, col, header)

        # 写入数据
        for row, training in enumerate(trainings, 1):
            mode_dict = dict(training._fields['training_mode'].selection)
            status_dict = dict(training._fields['status'].selection)

            data = [
                training.equipment_code,
                training.equipment_name,
                training.equipment_category,
                training.training_date.strftime('%Y-%m-%d') if training.training_date else '',
                training.training_content or '',
                mode_dict.get(training.training_mode, training.training_mode),
                training.trainer_name,
                training.participant_count,
                training.department_name,
                training.duration_hours,
                training.training_location or '',
                training.training_score,
                status_dict.get(training.status, training.status),
                training.create_time.strftime('%Y-%m-%d %H:%M:%S') if training.create_time else '',
                training.remark or ''
            ]

            for col, value in enumerate(data):
                worksheet.write(row, col, value)

        workbook.close()
        output.seek(0)

        # 生成文件名
        filename = f"设备培训信息_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"

        response = request.make_response(
            output.getvalue(),
            headers=[
                ('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
                ('Content-Disposition', f'attachment; filename="{filename}"')
            ]
        )
        output.close()
        return response

        # ==================== 设备巡检管理 ====================

    @http.route('/api/inspection/list', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:inspection:list')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def list_inspection(self, **kwargs):
        """获取设备巡检列表"""
        page = kwargs.get('pageNum', 1)
        size = kwargs.get('pageSize', 10)
        equipment_id = kwargs.get('equipmentId', '')
        equipment_name = kwargs.get('equipmentName', '')
        inspector_name = kwargs.get('inspectorName', '')
        inspection_type = kwargs.get('inspectionType', '')
        status = kwargs.get('status', '')
        result = kwargs.get('result', '')

        domain = []
        if equipment_id:
            domain.append(('equipment_id', '=', int(equipment_id)))
        if equipment_name:
            domain.append(('equipment_name', 'ilike', equipment_name))
        if inspector_name:
            domain.append(('inspector_name', 'ilike', inspector_name))
        if inspection_type:
            domain.append(('inspection_type', '=', inspection_type))
        if status:
            domain.append(('status', '=', status))
        if result:
            domain.append(('result', '=', result))

        # 部门权限过滤
        current_user = getattr(request, 'current_api_user', None)
        if current_user:
            # 检查是否是admin账号，admin账号拥有全部权限
            if hasattr(current_user, 'is_admin') and current_user.is_admin:
                # admin账号可以看到所有巡检记录，不添加过滤条件
                pass
            else:
                user_department = current_user.department_id
                if user_department:
                    # 检查用户是否是部门负责人
                    is_department_leader = user_department.leader_id and user_department.leader_id.id == current_user.id

                    if is_department_leader:
                        # 部门负责人：可以看到该部门下的所有设备相关巡检
                        equipment_ids = request.env['device.equipment'].search([
                            ('department_id', '=', user_department.id)
                        ]).ids
                        if equipment_ids:
                            domain.append(('equipment_id', 'in', equipment_ids))
                        else:
                            domain.append(('id', '=', False))
                    else:
                        # 非部门负责人：只能看到设备绑定用户为自己的巡检记录
                        equipment_ids = request.env['device.equipment'].search([
                            ('user_id', '=', current_user.id)
                        ]).ids
                        if equipment_ids:
                            domain.append(('equipment_id', 'in', equipment_ids))
                        else:
                            # 如果没有绑定设备，返回空结果
                            domain.append(('id', '=', False))
                else:
                    # 没有部门信息，返回空结果
                    domain.append(('id', '=', False))

        # 计算总数
        total = request.env['device.inspection'].search_count(domain)

        # 获取数据
        offset = (page - 1) * size
        inspections = request.env['device.inspection'].search(domain, offset=offset, limit=size,
                                                              order='inspection_date desc')

        # 构建返回数据
        rows = []
        for inspection in inspections:
            rows.append({
                'inspectionId': inspection.id,
                'equipmentId': inspection.equipment_id.id,
                'equipmentName': inspection.equipment_name,
                'equipmentCode': inspection.equipment_code,
                'equipmentCategory': inspection.equipment_category,
                'inspectionDate': inspection.inspection_date.strftime('%Y-%m-%d') if inspection.inspection_date else '',
                'inspectionContent': inspection.inspection_content or '',
                'inspectorId': inspection.inspector_id.id if inspection.inspector_id else None,
                'inspectorName': inspection.inspector_name,
                'inspectionType': inspection.inspection_type,
                'status': inspection.status,
                'result': inspection.result,
                'problemDescription': inspection.problem_description or '',
                'solution': inspection.solution or '',
                'durationMinutes': inspection.duration_minutes,
                'createTime': inspection.create_time.strftime('%Y-%m-%d %H:%M:%S') if inspection.create_time else '',
                'remark': inspection.remark or ''
            })

        return {
            'code': 200,
            'message': '',
            'data': {
                'total': total,
                'rows': rows
            }
        }

    @http.route('/api/inspection/add', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:inspection:add')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def add_inspection(self, **kwargs):
        """新增巡检记录"""
        equipment_id = kwargs.get('equipmentId')
        inspection_date = kwargs.get('inspectionDate')
        inspection_content = kwargs.get('inspectionContent')
        inspector_id = kwargs.get('inspectorId')
        inspection_type = kwargs.get('inspectionType', 'routine')
        result = kwargs.get('result', 'normal')
        duration_minutes = kwargs.get('durationMinutes', 30)
        problem_description = kwargs.get('problemDescription', '')
        solution = kwargs.get('solution', '')
        remark = kwargs.get('remark', '')

        if not equipment_id or not inspection_date or not inspection_content or not inspector_id:
            raise ValidationError('设备、巡检日期、巡检内容、巡检人为必填项')

        vals = {
            'equipment_id': int(equipment_id),
            'inspection_date': datetime.strptime(inspection_date, '%Y-%m-%d').date(),
            'inspection_content': inspection_content,
            'inspector_id': int(inspector_id),
            'inspection_type': inspection_type,
            'result': result,
            'duration_minutes': int(duration_minutes),
            'problem_description': problem_description,
            'solution': solution,
            'remark': remark
        }

        inspection = request.env['device.inspection'].create(vals)
        return {
            'code': 200,
            'message': '',
            'data': {'inspectionId': inspection.id}
        }

    @http.route('/api/inspection/export', type='http', auth='none', methods=['GET'], csrf=False, cors='*')
    @verify_api_token
    # @check_api_permission('device:inspection:export')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def export_inspection(self, **kwargs):
        """导出巡检信息"""

        inspections = request.env['device.inspection'].search([])

        # 构建Excel数据
        import xlsxwriter
        output = io.BytesIO()
        workbook = xlsxwriter.Workbook(output)
        worksheet = workbook.add_worksheet('设备巡检信息')

        # 设置标题
        headers = [
            '设备编号', '设备名称', '设备类别', '巡检日期', '巡检内容', '巡检人',
            '巡检类型', '巡检状态', '巡检结果', '问题描述', '解决方案',
            '巡检时长(分钟)', '创建时间', '备注'
        ]

        # 写入标题
        for col, header in enumerate(headers):
            worksheet.write(0, col, header)

        # 写入数据
        for row, inspection in enumerate(inspections, 1):
            type_dict = dict(inspection._fields['inspection_type'].selection)
            status_dict = dict(inspection._fields['status'].selection)
            result_dict = dict(inspection._fields['result'].selection)

            data = [
                inspection.equipment_code,
                inspection.equipment_name,
                inspection.equipment_category,
                inspection.inspection_date.strftime('%Y-%m-%d') if inspection.inspection_date else '',
                inspection.inspection_content or '',
                inspection.inspector_name,
                type_dict.get(inspection.inspection_type, inspection.inspection_type),
                status_dict.get(inspection.status, inspection.status),
                result_dict.get(inspection.result, inspection.result),
                inspection.problem_description or '',
                inspection.solution or '',
                inspection.duration_minutes,
                inspection.create_time.strftime('%Y-%m-%d %H:%M:%S') if inspection.create_time else '',
                inspection.remark or ''
            ]

            for col, value in enumerate(data):
                worksheet.write(row, col, value)

        workbook.close()
        output.seek(0)

        # 生成文件名
        filename = f"设备巡检信息_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"

        response = request.make_response(
            output.getvalue(),
            headers=[
                ('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
                ('Content-Disposition', f'attachment; filename="{filename}"')
            ]
        )
        output.close()
        return response

        # ==================== 设备验证管理 ====================

    @http.route('/api/verification/list', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:verification:list')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def list_verification(self, **kwargs):
        """获取设备验证列表"""
        page = kwargs.get('pageNum', 1)
        size = kwargs.get('pageSize', 10)
        equipment_id = kwargs.get('equipmentId', '')
        equipment_name = kwargs.get('equipmentName', '')
        internal_code = kwargs.get('internalCode', '')
        verification_type = kwargs.get('verificationType', '')
        status = kwargs.get('status', '')

        domain = []
        if equipment_id:
            domain.append(('equipment_id', '=', int(equipment_id)))
        if equipment_name:
            domain.append(('equipment_name', 'ilike', equipment_name))
        if internal_code:
            domain.append(('internal_code', 'ilike', internal_code))
        if verification_type:
            domain.append(('verification_type', '=', verification_type))
        if status:
            domain.append(('status', '=', status))

        # 部门权限过滤
        current_user = getattr(request, 'current_api_user', None)
        if current_user:
            # 检查是否是admin账号，admin账号拥有全部权限
            if hasattr(current_user, 'is_admin') and current_user.is_admin:
                # admin账号可以看到所有验证记录，不添加过滤条件
                pass
            else:
                user_department = current_user.department_id
                if user_department:
                    # 检查用户是否是部门负责人
                    is_department_leader = user_department.leader_id and user_department.leader_id.id == current_user.id

                    if is_department_leader:
                        # 部门负责人：可以看到该部门下的所有设备相关验证
                        equipment_ids = request.env['device.equipment'].search([
                            ('department_id', '=', user_department.id)
                        ]).ids
                        if equipment_ids:
                            domain.append(('equipment_id', 'in', equipment_ids))
                        else:
                            domain.append(('id', '=', False))
                    else:
                        # 非部门负责人：只能看到设备绑定用户为自己的验证记录
                        equipment_ids = request.env['device.equipment'].search([
                            ('user_id', '=', current_user.id)
                        ]).ids
                        if equipment_ids:
                            domain.append(('equipment_id', 'in', equipment_ids))
                        else:
                            # 如果没有绑定设备，返回空结果
                            domain.append(('id', '=', False))
                else:
                    # 没有部门信息，返回空结果
                    domain.append(('id', '=', False))

        # 计算总数
        total = request.env['device.verification'].search_count(domain)

        # 获取数据
        offset = (page - 1) * size
        verifications = request.env['device.verification'].search(domain, offset=offset, limit=size,
                                                                  order='verification_date desc')

        # 构建返回数据
        rows = []
        for verification in verifications:
            rows.append({
                'verificationId': verification.id,
                'equipmentId': verification.equipment_id.id,
                'equipmentName': verification.equipment_name,
                'equipmentCode': verification.equipment_code,
                'equipmentCategory': verification.equipment_category,
                'verificationDate': verification.verification_date.strftime(
                    '%Y-%m-%d') if verification.verification_date else '',
                'verificationCycle': verification.verification_cycle,
                'nextVerificationDate': verification.next_verification_date.strftime(
                    '%Y-%m-%d') if verification.next_verification_date else '',
                'internalCode': verification.internal_code,
                'verificationType': verification.verification_type,
                'status': verification.status,
                'verificationAgency': verification.verification_agency or '',
                'verifier': verification.verifier or '',
                'verificationResult': verification.verification_result or '',
                'conclusion': verification.conclusion or '',
                'createTime': verification.create_time.strftime(
                    '%Y-%m-%d %H:%M:%S') if verification.create_time else '',
                'remark': verification.remark or ''
            })

        return {
            'code': 200,
            'message': '',
            'data': {
                'total': total,
                'rows': rows
            }
        }

    @http.route('/api/verification/add', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:verification:add')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def add_verification(self, **kwargs):
        """新增验证记录"""
        equipment_id = kwargs.get('equipmentId')
        verification_date = kwargs.get('verificationDate')
        verification_cycle = kwargs.get('verificationCycle')
        internal_code = kwargs.get('internalCode')
        verification_type = kwargs.get('verificationType', 'periodic')
        verification_agency = kwargs.get('verificationAgency', '')
        verifier = kwargs.get('verifier', '')
        remark = kwargs.get('remark', '')

        if not equipment_id or not verification_date or not verification_cycle or not internal_code:
            raise ValidationError('设备、验证日期、验证周期、内部编码为必填项')

        vals = {
            'equipment_id': int(equipment_id),
            'verification_date': datetime.strptime(verification_date, '%Y-%m-%d').date(),
            'verification_cycle': int(verification_cycle),
            'internal_code': internal_code,
            'verification_type': verification_type,
            'verification_agency': verification_agency,
            'verifier': verifier,
            'remark': remark
        }

        verification = request.env['device.verification'].create(vals)
        return {
            'code': 200,
            'message': '',
            'data': {'verificationId': verification.id}
        }

        # ==================== 设备校准管理 ====================

    @http.route('/api/calibration/list', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:calibration:list')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def list_calibration(self, **kwargs):
        """获取设备校准列表"""
        page = kwargs.get('pageNum', 1)
        size = kwargs.get('pageSize', 10)
        equipment_id = kwargs.get('equipmentId', '')
        equipment_name = kwargs.get('equipmentName', '')
        internal_number = kwargs.get('internalNumber', '')
        calibration_type = kwargs.get('calibrationType', '')
        status = kwargs.get('status', '')

        domain = []
        if equipment_id:
            domain.append(('equipment_id', '=', int(equipment_id)))
        if equipment_name:
            domain.append(('equipment_name', 'ilike', equipment_name))
        if internal_number:
            domain.append(('internal_number', 'ilike', internal_number))
        if calibration_type:
            domain.append(('calibration_type', '=', calibration_type))
        if status:
            domain.append(('status', '=', status))

        # 部门权限过滤
        current_user = getattr(request, 'current_api_user', None)
        if current_user:
            # 检查是否是admin账号，admin账号拥有全部权限
            if hasattr(current_user, 'is_admin') and current_user.is_admin:
                # admin账号可以看到所有校准记录，不添加过滤条件
                pass
            else:
                user_department = current_user.department_id
                if user_department:
                    # 检查用户是否是部门负责人
                    is_department_leader = user_department.leader_id and user_department.leader_id.id == current_user.id

                    if is_department_leader:
                        # 部门负责人：可以看到该部门下的所有设备相关校准
                        equipment_ids = request.env['device.equipment'].search([
                            ('department_id', '=', user_department.id)
                        ]).ids
                        if equipment_ids:
                            domain.append(('equipment_id', 'in', equipment_ids))
                        else:
                            domain.append(('id', '=', False))
                    else:
                        # 非部门负责人：只能看到设备绑定用户为自己的校准记录
                        equipment_ids = request.env['device.equipment'].search([
                            ('user_id', '=', current_user.id)
                        ]).ids
                        if equipment_ids:
                            domain.append(('equipment_id', 'in', equipment_ids))
                        else:
                            # 如果没有绑定设备，返回空结果
                            domain.append(('id', '=', False))
                else:
                    # 没有部门信息，返回空结果
                    domain.append(('id', '=', False))

        # 计算总数
        total = request.env['device.calibration'].search_count(domain)

        # 获取数据
        offset = (page - 1) * size
        calibrations = request.env['device.calibration'].search(domain, offset=offset, limit=size,
                                                                order='calibration_date desc')

        # 构建返回数据
        rows = []
        for calibration in calibrations:
            rows.append({
                'calibrationId': calibration.id,
                'equipmentId': calibration.equipment_id.id,
                'equipmentName': calibration.equipment_name,
                'equipmentCode': calibration.equipment_code,
                'equipmentCategory': calibration.equipment_category,
                'calibrationDate': calibration.calibration_date.strftime(
                    '%Y-%m-%d') if calibration.calibration_date else '',
                'calibrationCycle': calibration.calibration_cycle,
                'nextCalibrationDate': calibration.next_calibration_date.strftime(
                    '%Y-%m-%d') if calibration.next_calibration_date else '',
                'internalNumber': calibration.internal_number,
                'calibrationType': calibration.calibration_type,
                'status': calibration.status,
                'calibrationAgency': calibration.calibration_agency or '',
                'calibrator': calibration.calibrator or '',
                'certificateNumber': calibration.certificate_number or '',
                'calibrationResult': calibration.calibration_result or '',
                'conclusion': calibration.conclusion or '',
                'createTime': calibration.create_time.strftime('%Y-%m-%d %H:%M:%S') if calibration.create_time else '',
                'remark': calibration.remark or ''
            })
        return {
            'code': 200,
            'message': '',
            'data': {
                'total': total,
                'rows': rows
            }
        }

    @http.route('/api/calibration/add', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    # @api_response
    @verify_api_token
    # @check_api_permission('device:calibration:add')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def add_calibration(self, **kwargs):
        """新增校准记录"""
        equipment_id = kwargs.get('equipmentId')
        calibration_date = kwargs.get('calibrationDate')
        calibration_cycle = kwargs.get('calibrationCycle')
        internal_number = kwargs.get('internalNumber')
        calibration_type = kwargs.get('calibrationType', 'periodic')
        calibration_agency = kwargs.get('calibrationAgency', '')
        calibrator = kwargs.get('calibrator', '')
        certificate_number = kwargs.get('certificateNumber', '')
        remark = kwargs.get('remark', '')

        if not equipment_id or not calibration_date or not calibration_cycle or not internal_number:
            raise ValidationError('设备、校准日期、校准周期、内部编号为必填项')

        vals = {
            'equipment_id': int(equipment_id),
            'calibration_date': datetime.strptime(calibration_date, '%Y-%m-%d').date(),
            'calibration_cycle': int(calibration_cycle),
            'internal_number': internal_number,
            'calibration_type': calibration_type,
            'calibration_agency': calibration_agency,
            'calibrator': calibrator,
            'certificate_number': certificate_number,
            'remark': remark
        }

        calibration = request.env['device.calibration'].create(vals)
        return {
            'code': 200,
            'message': '',
            'data': {'calibrationId': calibration.id}
        }
